<template>
  <div class="login_container">
    <div class="login_box">
      <!-- 表单区域 -->
      <el-form class="login_form" ref="loginFormRef" :rules="loginFormRules" :model="loginForm" label-width="80px">
        <el-form-item label="登录账户" prop="username">
          <el-input v-model="loginForm.username" :prefix-icon="iconAvatar" clearable placeholder="请输入登陆账号"></el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="loginForm.password" :prefix-icon="iconLock" clearable placeholder="请输入登陆密码" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-row justify="center">
            <el-col :span="12">
              <el-button type="primary" class="btnLeft" plain @click="chooseUser('user')">普通用户</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="success" class="btnRight" plain @click="chooseUser('admin')">超级管理员</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="" label-width="0px" class="login_btn">
          <el-button type="primary" @click="login" :loading="loginLoading">{{ loginBtnTxt }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  name: "Login",
};
</script>
<script setup>
import { getCurrentInstance, ref, reactive, toRefs } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { postLogin } from "network/user";
import { messageUtils } from "assets/js/messageUtils";
import { localStorageUtils } from "assets/js/utils";
// //setup写在script标签中,父子组件通讯及获取上下文的方法
// // import { useContext, defineProps, defineEmits } from 'vue'
// //  // defineProps 用来接收父组件传来的值props。
// //
// //  // defineEmits 用来声明触发的事件表。
// //
// //  // useContext 用来获取组件上下文context。
// // ​
// // const emit = defineEmits(['child-click'])
// // const ctx = useContext()
// // const props = defineProps({  // 可以拿到它的值
// //   msg: String,
// // })
// // ​
// // const sonClick = () => {
// //   emit('child-click', ctx)
// // }

const { proxy } = getCurrentInstance();
const router = useRouter();
const store = useStore();
//标签
const iconName = ref("Search");
const iconLock = ref("Lock");
const iconAvatar = ref("Avatar");
//变量
const loginForm = reactive({
  username: "",
  password: "",
});
const loginFormRef = ref(null);
const loginLoading = ref(false);
const loginBtnTxt = ref("登录");
//自定义表单校验  用默认的校验前面会有红色的*号  不太雅观
const validateName = (rule, value, callback) => {
  if (value.trim() === "") {
    callback(new Error("请输入账号"));
  } else {
    if (loginForm.username.trim() !== "") {
      loginFormRef.value.validateField("username");
    }
    callback();
  }
};
const validatePwd = (rule, value, callback) => {
  if (value.trim() === "") {
    callback(new Error("请输入密码"));
  } else {
    if (loginForm.password.trim() !== "") {
      loginFormRef.value.validateField("password");
    }
    callback();
  }
};
//定义校验规则
const loginFormRules = reactive({
  username: [
    { validator: validateName, trigger: "blur" },
    //{ min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' } 自定义验证之后这个就没有用了
  ],
  password: [
    { validator: validatePwd, trigger: "blur" },
    //{ min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ],
});
//切换用户
const chooseUser = (userType) => {
  if (userType === "user") {
    loginFormRef.value.resetFields(); //清空表单
  } else if (userType === "admin") {
    loginForm.username = "admin";
    loginForm.password = "123";
  }
};
//登录
const login = () => {
  loginFormRef.value.validate(async (valid) => {
    loginLoading.value = true;
    loginBtnTxt.value = "数据校验中...";
    if (valid) {
      //后端验证
      //页面跳转  replace不可以退回   push可以退回
      try {
        const res = await postLogin(loginForm);
        if (!res.success) return proxy.$notify.error({ message: res.msg, showClose: true });
        //记录过期时间和刷新时间
        let curTime = new Date();
        res.response.expirationTime = new Date(curTime.setSeconds(curTime.getSeconds() + res.response.expiration));
        res.response.refreshTime = res.response.expirationTime;
        //存储token信息
        res.response.token = res.response.tokenType + " " + res.response.token;
        store.commit("user/setUserInformation", res.response);
        //弹出登陆成功提示框
        proxy.$notify.success({ message: res.msg, showClose: true });
        router.push("/home"); //跳转
        loginFormRef.value.resetFields(); //清空表单
      } catch (error) {
        proxy.$notify.error({ message: error, showClose: true });
        loginBtnTxt.value = "登录";
        loginLoading.value = false;
      }
    }
    loginBtnTxt.value = "登录";
    loginLoading.value = false;
  });
};
</script>

<style lang="less" scoped>
.login_container {
  background-color: #2b4b6b;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px; //角变成圆角
  position: relative; //父相子绝
  display: flex;
  justify-content: center;
  align-items: center;
}
.login_form {
  width: 100%;
  padding: 0 20px;
}
.login_btn {
  width: 100%;
  button {
    width: 100%;
  }
}
</style>
